<?php

namespace App\Http\Controllers;

use App\Exceptions\ApiException;
use App\Exports\UsersExport;
use App\Imports\UsersImport;
use App\Models\Project;
use App\Models\User;
use App\Services\CommonService;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use PHPUnit\Util\Exception;

/**
 * 用户控制器类
 * Class UserController
 * @package App\Http\Controllers
 */
class UserController extends Controller
{
    public $userService;

    public function __construct(UserService $userService)
    {
        parent::__construct();
        $this->userService = $userService;
    }

    /**
     * 用户列表
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 11:11
     */
    public function index(Request $request): JsonResponse
    {
        $perPage = $request->input('per_page') ?: $this->limit;

        $list = $this->userService->getList($request->all(), $perPage);

        return $this->success($list);
    }

    /**
     * 获取项目列表（用户筛选用） 只有超管能看到，所以是全部项目
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 11:11
     */
    public function getProjectList(): JsonResponse
    {
        $list = Project::query()->get()->toArray();

        return $this->success($list);
    }

    /**
     * 通过名称模糊搜索用户
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:51
     */
    public function searchUsers(Request $request): JsonResponse
    {
        $name = $request->input('name');

        $data = $this->userService->getUsers($name);

        return $this->success($data);
    }

    /**
     * 查询单个数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:53
     */
    public function show(Request $request): JsonResponse
    {
        $id   = $request->input('id');
        $data = $this->userService->getInfo($id);

        return $this->success($data);
    }

    /**
     * 通过手机号获取用户 （已注册并通过）
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:53
     */
    public function getUserByPhone(Request $request): JsonResponse
    {
        $phone = $request->input('phone');
        if (!is_phone_number($phone)) {
            return $this->error('手机号不合法！');
        }
        if (!$user = UserService::getUserByPhone($phone)) {
            return $this->error('用户不存在或暂未审核！');
        }
        $data = $this->userService->getUserCompanyRoles($user->id);

        return $this->success($data);
    }

    /**
     * 新增用户
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/2/26 10:54
     */
    public function store(Request $request): JsonResponse
    {
        $this->userService->saveBaseData($request->all());

        $msg = $request->input('id') ? '修改成功' : '添加成功！';

        return $this->success('', $msg);
    }

    /**
     * 更新一条用户信息，传哪些字段就会更新哪些字段
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/2/26 10:54
     */
    public function update(Request $request): JsonResponse
    {
        $params = $request->all();
        if (empty($params['company_id'])) { //在用户列表更新
            $result = $this->userService->updateData($params);
            if ($result['msg']) return $this->error($result['msg']);
        } else { //在组织架构更新
            $this->userService->updateUserInOrganize($params);
        }

        return $this->success('', '修改成功！');
    }

    /**
     * 获取用户所在的公司
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:56
     */
    public function companies(): JsonResponse
    {
        $companies = $this->userService->companies();

        return $this->success($companies);
    }

    /**
     * 获取用户所在的全部公司，以及在每个公司全部的角色
     *
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:56
     */
    public function userDetails(): JsonResponse
    {
        $userId = user_id();

        $userWithRelation = $this->userService->userDetails($userId);

        return $this->success($userWithRelation);
    }

    /**
     * 设置当前登录选中的公司id
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:57
     */
    public function setCompanyId(Request $request): JsonResponse
    {
        $companyId = $request->input('id') ?: 0;
        if (!$result = $this->userService->setCompanyId($companyId)) {
            return $this->error('设置失败！');
        }

        return $this->success($result, '操作成功！');
    }

    /**
     * 导入用户
     *
     * @param Request $request
     * @return JsonResponse
     * @throws ApiException
     * @author: lxk
     * @date: 2024/2/26 10:57
     */
    public function import(Request $request): JsonResponse
    {
        try {
            $this->userService->isFileValid($request);//验证文件是否合法
            Excel::import(new UsersImport(), $request->file('file'));
            CommonService::addActionLog('导入用户');
            return $this->success('', '导入成功');
        } catch (Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 导出用户
     *
     * @return JsonResponse|\Symfony\Component\HttpFoundation\BinaryFileResponse
     * @author: lxk
     * @date: 2024/2/26 10:57
     */
    public function export()
    {
        return Excel::download(new UsersExport(), date('Ymd') . '用户数据.xlsx');
    }

    /**
     * 用户操作记录
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:57
     */
    public function actionLogs(Request $request): JsonResponse
    {
        $perPage = $request->input('per_page') ?: $this->limit;

        $list = $this->userService->getActionLogList($request, $perPage);

        return $this->success($list);
    }

    /**
     * 转让账号 转让的时候让用户输入登录账户，确认后才可以
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 10:58
     */
    public function transferAccount(Request $request): JsonResponse
    {
        $nickname = format_str($request->input('nickname')); //新用户名称
        $phone    = $request->input('phone'); //新用户手机号
        if (!is_phone_number($phone)) {
            return $this->error('手机号不合法！');
        }
        $this->userService->transferAdmin($phone, $nickname);

        return $this->success('', '转让成功！初始密码和手机号一致，请通知用户并及时修改！');
    }

    /**
     * 回收站列表（进行软删除的数据）
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 11:03
     */
    public function recycle(Request $request): JsonResponse
    {
        $data = $this->userService->getRecycles($request);

        return $this->success($data);
    }

    /**
     * 批量软删除，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 11:03
     */
    public function destroyMore(Request $request): JsonResponse
    {
        $ids = to_array($request->input('ids'));
        if (!User::destroy($ids)) {
            return $this->error('删除失败！');
        };
        $ids = implode(',', $ids);
        CommonService::addActionLog("删除用户", "【数据ID={$ids}】");

        return $this->success('', '已放入回收站');
    }

    /**
     * 恢复批量数据
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 11:02
     */
    public function retrieveMore(Request $request): JsonResponse
    {
        $ids = to_array($request->input('ids'));
        if (!User::query()->whereIn('id', $ids)->restore()) {
            return $this->error('恢复失败！');
        }
        $ids = implode(',', $ids);
        CommonService::addActionLog("恢复用户", "【数据ID={$ids}】");

        return $this->success('', '恢复成功');
    }

    /**
     * 永久删除批量数据，ids可以是以","逗号分割的字符串，也可以是数组形式
     *
     * @param Request $request
     * @return JsonResponse
     * @author: lxk
     * @date: 2024/2/26 11:02
     */
    public function deleteMore(Request $request): JsonResponse
    {
        $ids = to_array($request->input('ids'));
        if (!User::withTrashed()->whereIn('id', $ids)->forceDelete()) {
            return $this->error('删除失败！');
        }
        $ids = implode(',', $ids);
        CommonService::addActionLog("永久删除用户", "【数据ID={$ids}】");

        return $this->success('', '删除成功');
    }

    /**
     * 把系统用户密码重置
     *
     * @param Request $request
     * @return JsonResponse
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @author: lxk
     * @date: 2025-07-21 18:01
     */
    public function resetSystemUsersPassword(Request $request) : JsonResponse
    {
        $type     = $request->input('type');
        $prefix   = $request->input('prefix');
        $redisKey = 'effectUserCount:' . get_rand_str();
        redis()->set($redisKey, 0);
        $this->userService->resetSystemUsersPassword($type, $prefix, $redisKey);
        $effectUserCount = redis()->get($redisKey);
        redis()->del($redisKey);

        return $this->success('', "操作成功！影响【{$effectUserCount}】位用户");
    }




}
